package thread;

import org.junit.Test;

import java.util.Arrays;
import java.util.concurrent.*;

/**
 * 线程池
 * @author Duanyu
 * @date 2021-11-09 17:08
 */
public class ThreadPoolTest {

    /**
     * 1.线程池接口体系：
     *  java.util.concurrent.Executor：负责线程的使用与调度的根接口
     *   -> ExecutorService：线程池的主要接口
     *      --> ThreadPoolExecutor：线程池的实现类
     *      -> ScheduleExecutorService ：负责线程的调度
     *          ->ScheduledThreadPoolExecutor：继承于 ThreadPoolExecutor又实现了 ScheduleExecutorService
     * 2.Executors工具类：
     *
     *      newFixedThreadPool()：创建指定大小的线程池
     *      newCachedThreadPool()：缓存线程池,线程池数量根据需求自动更改数量
     *      newSingleThreadExecutor()：创建单个线程池，线程池中只有一个线程
     *      newScheduledThreadPool()：创建指定大小的线程，可以延迟或定时的执行任务
     */

    @Test
    public void test3() {
        ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(
                8,
                16,
                60L, TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(2000),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.DiscardOldestPolicy()
        );

        poolExecutor.submit(()->1024);

        poolExecutor.execute(()-> {});

    }

    @Test
    public void test1() throws ExecutionException, InterruptedException {
        //创建线程池
        ExecutorService pool = Executors.newFixedThreadPool(5);

        //使用线程池为它分配任务
        Future<Integer> future = pool.submit(() -> {
            int sum = 0;
            for (int i = 1; i <= 100000; i++) {
                sum += i;
            }
            return sum;
        });

        System.out.println(future.get());

        //关闭线程池(任务执行完后关闭)
        pool.shutdown();

    }

    @Test
    public void test2() throws ExecutionException, InterruptedException {
        ScheduledExecutorService pool = Executors.newScheduledThreadPool(3);
        for (String s : Arrays.asList("1","2","3","4","5")){
            Future<String> schedule = pool.schedule(() -> {
                int sum = 0;
                for (int i = 1; i <= 10000; i++) {
                    sum += i;
                }
                return Thread.currentThread().getName()+":"+sum;
            }, 3L, TimeUnit.SECONDS);
            System.out.println(schedule.get());
        }
        pool.shutdown();
    }


}
